package edu.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import edu.core.PaginationSortOrderData;

/**
 * DAO的父类.
 *
 * @author weidong
 */

@Repository("baseDao")
public class BaseDao {
	@Autowired
	private SessionFactory sessionFactory;	
	
	public Session getSession() {
		if (sessionFactory != null) {
			if (sessionFactory.getCurrentSession() != null) {
				return sessionFactory.getCurrentSession();
			} else {
				return sessionFactory.openSession();
			}
		}
		return null;
	}

    public int batchDeleteByHql(String hql) throws Exception {
    	Query query = getSession().createQuery(hql);
    	int delCount = query.executeUpdate();
    	return delCount;
    }
    
	public Object selectObjById(Class clazz, String id) throws Exception {
		return getSession().get(clazz, id);
	}

	public void insert(Object obj) throws Exception {
		getSession().save(obj);
	}

	public void update(Object obj) throws Exception {
		getSession().update(obj);
	}

	public void delete(Object obj) throws Exception {
		getSession().delete(obj);
	}
	public void deleteById(Class clazz, String id) throws Exception {
		Object obj = selectObjById(clazz, id);
		getSession().delete(obj);
	}

	public List selectAllByEntityClassName(Class entityClass) throws Exception {
		String hql = "from " + entityClass.getSimpleName() + "";
		return getSession().createQuery(hql).list();
	}

	public List selectPojoByHql(String hql) throws Exception {
		List list = getSession().createQuery(hql).list();
		return list;
	}

	public int batchUpdateBySql(String sql) throws Exception {
		SQLQuery sqlQuery = getSession().createSQLQuery(sql);
		int count = sqlQuery.executeUpdate();
		return count;
	}

	public PaginationSortOrderData selectPojoByPage(Class clazz, PaginationSortOrderData frontPage, 
			List<String> conditionList, String orderBySql) throws Exception {
		String hql = "from " + clazz.getSimpleName() ;
		String totalCountSql = "select count(id) from " + clazz.getSimpleName() ;
		
		String whereHql = " where 1=1 ";
		
		if (conditionList != null && conditionList.size() > 0) {
			for (String obj : conditionList) {
				whereHql +=obj;
			}
		}
		Query query = getSession().createQuery(hql+whereHql + orderBySql);
		List list = this.getSession().createQuery(totalCountSql+whereHql).list();
		long totalProperty = (Long)list.get(0);
		
		// 总记录条数设定
		frontPage.setRowCount(Integer.parseInt(String.valueOf(totalProperty)));//先调用
		
		query.setFirstResult((int)(frontPage.getCurPage()-1)*frontPage.getPageSize());
		query.setMaxResults((int)frontPage.getPageSize());
		
		frontPage.setDataList(query.list());//后调用
		
		return frontPage;
	}
}
